const db = require('../config/database');
const logger = require('../utils/logger');

class StatsController {
  // 获取统计数据
  async getStats(req, res) {
    try {
      // 总订单数
      const [totalOrders] = await db.query(
        'SELECT COUNT(*) as total FROM orders'
      );

      // 待支付订单数
      const [pendingOrders] = await db.query(
        'SELECT COUNT(*) as total FROM orders WHERE status = 0'
      );

      // 已支付订单数
      const [paidOrders] = await db.query(
        'SELECT COUNT(*) as total FROM orders WHERE status = 1'
      );

      // 总销售额（已支付订单）
      const [totalAmount] = await db.query(
        'SELECT SUM(product_price) as total FROM orders WHERE status = 1'
      );

      // 今日订单数
      const [todayOrders] = await db.query(
        'SELECT COUNT(*) as total FROM orders WHERE DATE(created_at) = CURDATE()'
      );

      // 今日销售额
      const [todayAmount] = await db.query(
        'SELECT SUM(product_price) as total FROM orders WHERE DATE(created_at) = CURDATE() AND status = 1'
      );

      res.json({
        success: true,
        data: {
          totalOrders: parseInt(totalOrders[0].total) || 0,
          pendingOrders: parseInt(pendingOrders[0].total) || 0,
          paidOrders: parseInt(paidOrders[0].total) || 0,
          totalAmount: parseFloat(totalAmount[0].total) || 0,
          todayOrders: parseInt(todayOrders[0].total) || 0,
          todayAmount: parseFloat(todayAmount[0].total) || 0
        }
      });
    } catch (error) {
      logger.error('获取统计数据失败', { error: error.message });
      res.json({ success: false, message: '获取统计数据失败' });
    }
  }

  // 获取最近7天的订单趋势
  async getOrderTrend(req, res) {
    try {
      const [trend] = await db.query(`
        SELECT 
          DATE(created_at) as date,
          COUNT(*) as total,
          SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as paid,
          SUM(CASE WHEN status = 1 THEN product_price ELSE 0 END) as amount
        FROM orders 
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
      `);

      res.json({
        success: true,
        data: trend
      });
    } catch (error) {
      logger.error('获取订单趋势失败', { error: error.message });
      res.json({ success: false, message: '获取订单趋势失败' });
    }
  }
}

module.exports = new StatsController();

